var express = require('express');
var router = express.Router();
let Query = require('../tools/db')
let ts = require('time-stamp')
let formidable = require('formidable')
let path = require('path')
let { suo, api_url, getToken, verifyToken } = require('../config/config');

//权限验证 获取token  存在req.headers.authorization
/*  router.use((req,res,next)=>{
  if(!verifyToken(req.headers.authorization)){
    next('token无效，请重新登录')
  }else{
    next()
  }
 }) */

//获取视频id获取课程的视频地址
router.get('/videoplay', async (req, res, next) => {
  let { id = '' } = req.query

  //id是必填项，不填则报错
  if (id == '') {
    next('id不能为空')
    return
  }

  let sql = `SELECT video_src FROM e_video WHERE id='${id}'`
  let [, result] = await Query(sql)
  result[0].video_src = `${api_url}/upload/video/${result[0].video_src}`
  res.send({
    code: 200,
    msg: 'ok',
    result: result[0].video_src
  })

})

//根据当前登录用户和课程id进行报名
router.post('/study', async (req, res, next) => {
  let { cid = '', mid = '' } = req.body

  //mid是必填项，不填则报错
  if (mid == '' || cid == '') {
    next('mid和cid不能为空')
    return
  }

  let sql1 = `SELECT * FROM e_order WHERE mid='${mid}' AND cid='${cid}'`
  let [, res1] = await Query(sql1)
  if (res1.length > 0) {
    next('该用户已经报名，不能重复报名')
    return
  }
  let oid = ts('YYYYMMDDHHmmss') + (Math.random() + '').substring(2, 8)
  let createdate = Date.now()
  let sql2 = `INSERT INTO e_order (oid,cid,mid,createdate,status) VALUES ('${oid}','${cid}','${mid}','${createdate}',1)`
  let [, result] = await Query(sql2)
  if (result.affectedRows > 0) {
    res.send({
      code: 200,
      msg: 'ok',
    })
  } else {
    next('报名失败，请稍后再试')
  }

})

//获取用户
router.get('/user', async (req, res, next) => {
  let { mid = '' } = req.query
  if (mid == '') {
    next('mid不能为空')
    return
  }
  let sql = `SELECT * FROM e_member WHERE mid='${mid}'`
  let [, result] = await Query(sql)
  if (result.length > 0) {
    delete result[0].password
    res.send({
      code: 200,
      msg: 'ok',
      result
    })
  } else {
    next('找不到该用户')
  }
})

//更新用户
router.put('/user', async (req, res, next) => {
  let { mid ='',realname='',password='',sex='',city='',birthdate=''} = req.body
  if (mid == '') {
    next('mid不能为空')
    return
  }
  let arr=[]
  if(realname!=''){
    arr.push(`realname="${realname}"`)
  }
  if(password!=''){
    arr.push(`password="${password}"`)
  }
  if(sex!=''){
    arr.push(`sex="${sex}"`)
  }
  if(city!=''){
    arr.push(`city="${city}"`)
  }
  if(birthdate!=''){
    arr.push(`birthdate="${birthdate}"`)
  }
  let str=arr.join(',')
  let sql=`UPDATE e_member SET ${str} WHERE mid="${mid}"`
  let [,result]=await Query(sql)
  if(result.affectedRows>0){
    res.send({
      code:200,
      msg: "信息更改成功"
    })
    return
  }else{
    next('修改失败，请稍后再试')
  }
})

// 更新用户头像
router.post("/uploadhead", (req, res, next) => {

  let mid = "484ada7f-e065-4a22-a2cd-248561b6162f"
  if (!mid) {
    next("请登录")
    return
  }
  // 文件操作  formidable
  const form = formidable({
    // 临时存储
    uploadDir: "temdir",
  });
  form.parse(req, async (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    //如果没有上传文件
    if (!files.file.size) {
      next("请输入文件")
      return
    }
    // 存储文件 
    // 源地址
    let sourePath = files.file.filepath
    //  新名字
    let filename = ts("YYYYMMDDHHmmss") + (Math.random() + "").substring(2, 8) + path.extname(files.file.originalFilename)
    //  新地址
    let newPath = path.join(__dirname, "../uploads/avatar", filename)
    //  剪切
    fs.renameSync(sourePath, newPath)
    // 数据库更新
    let sql = `UPDATE e_member SET head_photo_url="${filename}" WHERE mid="${mid}"`
    let [, result] = await Query(sql)

    if (result.affectedRows > 0) {
      res.send({
        code: 200,
        msg: "ok",
        result: `${api_url}/upload/avatar/${filename}`
      })
    } else {
      next("请稍后再试")
    }
  })
})

//查看学习记录
router.get('/orders',async (req,res,next)=>{
  let {mid}=req.query
  if(mid==''){
    next('mid不能为空')
    return
  }
  let sql=`SELECT * FROM e_order JOIN e_course ON e_order.cid=e_course.cid WHERE e_order.mid='${mid}'`
  let [,result]=await Query(sql)
  res.send(result)
  if(result1.length>0){
    res.send({
      code:200,
      msg:"ok",
      result
    })
  }else{
    next('请稍后再试')
  }
})

  module.exports = router